package gold.digger;

import gold.utils.InputUtil;

import java.util.*;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC907 {
    public long startExecuteTime = System.currentTimeMillis();

    /*
     * @param 此题目参考了别人代码
     * 这是因为问题情况较为复杂
     * 未来需要再次复习此道题目
     * 这题目确实很精妙，可以称之为hard难度
     * @return:
     */
    class Solution {
        public int sumSubarrayMins(int[] arr) {
            //arr[] = {1,7,5,2,4,3,9};
            //比如说 j为6 也就是子序列分别是 0-6 1-6 ... 6-6
            //那么0 1 2 3 4 5 6 索引分别为 1 2 2 2 3 3 9 那么就可以当成 1个1 3个2 2个3 1个9
            //又比如j为5
            //那么0 1 2 3 4 5 索引分别为 1 2 2 2 3 3
            //所以 for中的j就是表示他的下限 然后 其实stack中的count的和为j 也就是 0-j到j-j的序列
            //而cot就记录j-1的总和 然后从j-1变成j 进行维护
            Stack<PP> stack = new Stack();
            int ans = 0;
            int cot = 0;
            for (int j = 0; j < arr.length; j++) {
                int count = 1;  //自己本身
                while (!stack.isEmpty() && stack.peek().val >= arr[j]) {
                    PP top = stack.pop();
                    count += top.count;   //代替了几个数
                    cot -= top.val * top.count; //把之前记录的总数 减去将会被代替的数
                }
                stack.push(new PP(arr[j], count));
                cot += arr[j] * count;
                ans += cot;
                ans %= 1000000000 + 7;
            }
            return ans;
        }
    }

    class PP {
        //val为值
        //count为出现了几次
        int val;
        int count;

        public PP(int val, int count) {
            this.val = val;
            this.count = count;
        }
    }

    class Solution_Time_Exceed {
        public int factor = 1000000007;

        public int sumSubarrayMins(int[] arr) {
            if (null == arr || arr.length <= 0) return 0;

            int sum = 0;
            Stack<Integer> stack = new Stack<>();
            for (int i = 0; i < arr.length; i++) {
                stack.clear();
                for (int j = i; j < arr.length; j++) {
                    if (stack.isEmpty() || stack.peek() > arr[j]) {
                        sum = (sum + arr[j]) % factor;
                        stack.push(arr[j]);
                    } else {
                        sum = (sum + stack.peek()) % factor;
                    }
                }
            }

            return sum;
        }
    }

    public void run() {
        Solution solution = new Solution();
        int[] arr = InputUtil.toIntegerArray("[11,81,94,43,3]");
        System.out.println(solution.sumSubarrayMins(arr));
    }

    public static void main(String[] args) throws Exception {
        LC907 an = new LC907();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
